import { ref, reactive, computed, watch } from 'vue'
import { postGenerator, postUpdateRecord } from '@/api/3D-Generator'
import { ElMessage } from 'element-plus'
import request from '@/util/request'
import modelEventBus from '@/util/eventbus/modelEventBus'
import { useUserStore } from '@/store/user'
import { useModelHistory } from '@/hook/useModelHistory'
import { useNotificationStore } from '@/store/notification' // 新增通知store
import {
    convertToProxyUrl,
    convertModelDataToProxy,
    convertResultFilesToProxy,
    logUrlConversion
} from '@/util/replaceUrl'



export function useGenerator() {

    const userStore = useUserStore()
    const notificationStore = useNotificationStore() // 新增

    // ========== 当前模型（响应式） ==========
    const currentModel = ref(null)

    // ========== 生成器配置（响应式） ==========
    const generatorConfig = ref({
        mode: 'text',
        taskVersion: 'pro',
        textConfig: {
            prompt: '',
            style: 'realistic',
            quality: 'standard'
        },
        imageConfig: {
            type: 'single',
            singleFiles: [],
            multipleFiles: [],
            multipleAngles: {
                front: null, back: null, left: null, right: null, top: null, bottom: null
            }
        },
        commonConfig: {
            model: 'hunyuan-3d-v3.0',
            faceCount: 50000,
            generateType: 'Normal',
            resultFormat: 'GLB',
            enablePBR: false,
            resolution: 'medium',
            textureQuality: 'standard',
            optimizeForPrint: false
        }
    })

    // ========== 生成器状态（响应式） ==========
    const generatorState = reactive({
        isGenerating: false,
        progress: 0,
        status: 'idle',
        statusText: '预计需要 30-60 秒',
        result: null,
        error: null,
        jobId: null,
        requestId: null,
        remainingGenerations: 19,
        estimatedTime: 0,
        currentStep: '',
        validationErrors: []
    })

    // ========== 历史记录管理（使用新的Hook） ==========
    const {
        historyList,
        historyState,
        filterState,
        filteredHistory,
        totalSize,
        statusStats,
        typeStats,
        fetchHistoryRecords,
        refreshHistory,
        loadMoreHistory,
        initializeHistory,
        setFilters,
        setSortBy,
        deleteHistoryRecord,
        updateStarStatus,
        findRecordById,
        addNewRecord,
        transformHistoryData,
        formatFileSize,
        getStatusTagType,
        getStatusLabel,
        getTypeLabel,
        getStatusColor,
        getTypeColor
    } = useModelHistory()

    // ========== 轮询相关状态（响应式） ==========
    const pollingState = reactive({
        isPolling: false,
        pollInterval: null,
        maxPollAttempts: 180,
        currentAttempt: 0
    })

    // ========== 新增：SSE连接管理 ==========
    const sseState = reactive({
        connection: null,
        isConnected: false,
        reconnectAttempts: 0,
        maxReconnectAttempts: 5
    })

    // ========== 核心方法 ==========

    // 模型格式优先级定义
    const MODEL_FORMAT_PRIORITY = {
        'GLB': 1,
        'GLTF': 2,
        'OBJ': 3,
        'FBX': 4,
        'STL': 5,
        'USDZ': 6,
        'MP4': 7
    }

    // 获取原始URL的工具函数
    const getOriginalUrl = (proxyUrl) => {
        if (!proxyUrl) return null

        if (proxyUrl.includes('/api/proxy?url=')) {
            try {
                const urlParam = proxyUrl.split('/api/proxy?url=')[1]
                return decodeURIComponent(urlParam)
            } catch (error) {
                console.warn('解析代理URL失败:', error)
                return proxyUrl
            }
        }

        if (proxyUrl.startsWith('/api/proxy/')) {
            return proxyUrl.replace('/api/proxy/', '')
        }

        return proxyUrl
    }

    // 根据格式优先级选择最佳模型
    const selectBestModel = (resultFiles) => {
        if (!Array.isArray(resultFiles) || resultFiles.length === 0) {
            return null
        }

        console.log('[useGenerator] 可用模型格式:', resultFiles.map(f => f.Type))

        const sortedFiles = resultFiles.sort((a, b) => {
            const priorityA = MODEL_FORMAT_PRIORITY[a.Type] || 999
            const priorityB = MODEL_FORMAT_PRIORITY[b.Type] || 999
            return priorityA - priorityB
        })

        const selectedFile = sortedFiles[0]
        console.log('[useGenerator] 选择的模型格式:', selectedFile.Type)

        return selectedFile
    }

    // ========== 新增：SSE连接方法 ==========

    // 建立SSE连接
    const establishSSEConnection = (userId) => {
        try {
            if (sseState.connection) {
                sseState.connection.close()
            }

            const baseUrl = import.meta.env.VITE_API_BASE_URL;

            const eventSource = new EventSource(`${baseUrl}/api/v2/notifications/stream/${userId}`)

            eventSource.onopen = () => {
                console.log('[SSE] 连接已建立')
                sseState.isConnected = true
                sseState.reconnectAttempts = 0
            }

            eventSource.onmessage = (event) => {
                const message = event.data
                console.log('event-data: ', typeof event.data, event.data)
                if (message.startsWith('data: ')) {
                    const jsonStr = message.substring(6) // 移除 "data: " (6个字符)
                    try {
                        const data = JSON.parse(jsonStr)
                        console.log('收到SSE消息: ', data)
                        handleSSEMessage(data)
                    } catch (error) {
                        console.error('JSON解析失败:', error)
                    }
                }
            }

            eventSource.onerror = (error) => {
                console.error('[SSE] 连接错误:', error)
                sseState.isConnected = false

                // 尝试重连
                if (sseState.reconnectAttempts < sseState.maxReconnectAttempts) {
                    sseState.reconnectAttempts++
                    setTimeout(() => {
                        console.log(`[SSE] 尝试重连 ${sseState.reconnectAttempts}/${sseState.maxReconnectAttempts}`)
                        establishSSEConnection(userId)
                    }, 3000 * sseState.reconnectAttempts)
                }
            }

            sseState.connection = eventSource

        } catch (error) {
            console.error('[SSE] 建立连接失败:', error)
        }
    }

    // 处理SSE消息
    const handleSSEMessage = (data) => {
        console.log('[SSE] 收到消息:', data)

        switch (data.type) {
            case 'evaluation_completed':
                handleEvaluationCompleted(data.payload)
                break
            case 'evaluation_failed':
                handleEvaluationFailed(data.payload)
                break
            case 'connection_established':
                console.log('[SSE] 连接确认:', data.message)
                break
            case 'heartbeat':
                console.log('[SSE] 心跳:', data.timestamp)
                break
            default:
                console.log('[SSE] 未知消息类型:', data.type)
        }
    }

    // 处理评估完成
    const handleEvaluationCompleted = (payload) => {
        

        ElMessage.success('3D模型评估报告已生成，点击导航栏通知查看')
    }

    // 处理评估失败
    const handleEvaluationFailed = (payload) => {
        notificationStore.addNotification({
            id: `eval_fail_${Date.now()}`,
            type: 'evaluation_failed',
            title: '3D模型评估失败',
            message: payload.error || '评估过程中发生错误',
            isRead: false,
            createdAt: new Date().toISOString()
        })

        ElMessage.error('3D模型评估失败，请稍后重试')
    }

    // 获取参考图片URL的辅助函数
    const getReferenceImageUrl = () => {
        const config = generatorConfig.value

        if (config.mode === 'text') {
            // 文本模式没有参考图片
            return null
        } else if (config.mode === 'image') {
            if (config.imageConfig.type === 'single') {
                // 单张图片模式
                const singleFile = config.imageConfig.singleFiles[0]
                return singleFile?.uploadedUrl || null
            } else {
                // 多视角模式，使用正视图
                const frontImage = config.imageConfig.multipleAngles.front
                return frontImage?.uploadedUrl || null
            }
        }

        return null
    }

    // 请求生成评估报告 - 修改：添加参考图片参数
    const requestEvaluationReport = async (modelData, prompt, referenceImageUrl = null) => {
        console.log('[评估] 请求生成评估报告:', { modelData, prompt, referenceImageUrl })

        // 构建请求参数
        const requestParams = {
            model_3d_url: modelData.originalUrl || modelData.url,
            prompt: prompt || '3D模型生成',
            user_id: userStore.userInfo.userId
        }

        // 如果有参考图片，添加到请求参数中
        if (referenceImageUrl) {
            requestParams.reference_image = referenceImageUrl
        }

        await request.post('/api/v2/evaluation/evaluate-model-async', requestParams)

    }

    // 关闭SSE连接
    const closeSSEConnection = () => {
        if (sseState.connection) {
            sseState.connection.close()
            sseState.connection = null
            sseState.isConnected = false
            console.log('[SSE] 连接已关闭')
        }
    }

    // 更新生成记录到后端 - 使用原始URL
    const updateGenerationRecord = async (modelData, requestId) => {
        try {
            console.log('[useGenerator] 开始更新生成记录:', { modelData, requestId })

            const originalUrl = getOriginalUrl(modelData.url)

            console.log('[useGenerator] URL转换:', {
                proxyUrl: modelData.url,
                originalUrl: originalUrl
            })

            const updateData = {
                model3dUrl: originalUrl,
                requestId: requestId,
                status: 'FINISHED'
            }

            const dataArray = [updateData]

            console.log('[useGenerator] 更新记录参数(使用原始URL):', dataArray)

            const response = await postUpdateRecord(dataArray)
            console.log('[useGenerator] 更新记录成功:', response)

            return response
        } catch (error) {
            console.error('[useGenerator] 更新生成记录失败:', error)
            ElMessage.warning('记录更新失败，但模型生成成功')
            throw error
        }
    }

    // 设置当前模型 - 使用 EventBus 通知
    const setCurrentModel = (modelData) => {
        console.log('[useGenerator] 设置当前模型:', modelData)

        const convertedModelData = convertModelDataToProxy(modelData)

        currentModel.value = convertedModelData

        if (convertedModelData) {
            modelEventBus.emitModelChanged(convertedModelData)
        } else {
            modelEventBus.emitModelCleared()
        }
    }

    // 表单验证
    const validateForm = () => {
        const errors = []
        const config = generatorConfig.value

        if (config.mode === 'text') {
            const prompt = config.textConfig.prompt.trim()
            if (!prompt) {
                errors.push('请输入文本描述')
            } else if (prompt.length > 500) {
                errors.push('文本描述不能超过500个字符')
            }
        }

        if (config.mode === 'image') {
            if (config.imageConfig.type === 'single') {
                if (config.imageConfig.singleFiles.length === 0) {
                    errors.push('请上传一张图片')
                } else {
                    const file = config.imageConfig.singleFiles[0]
                    if (file.isUploading) {
                        errors.push('图片正在上传中，请等待上传完成')
                    } else if (!file.uploadedUrl) {
                        errors.push('图片上传失败，请重新上传')
                    }
                    if (file.size > 6 * 1024 * 1024) {
                        errors.push('图片大小不能超过6MB')
                    }
                }
            } else {
                const files = config.imageConfig.multipleFiles
                if (files.length < 2) {
                    errors.push('多角度模式请至少上传2张图片')
                }

                const frontImage = config.imageConfig.multipleAngles.front
                if (!frontImage) {
                    errors.push('正面视角图片为必传项')
                }

                const uploadingFiles = files.filter(file => file.isUploading)
                if (uploadingFiles.length > 0) {
                    errors.push(`还有 ${uploadingFiles.length} 张图片正在上传，请等待`)
                }

                const failedFiles = files.filter(file => !file.isUploading && !file.uploadedUrl)
                if (failedFiles.length > 0) {
                    errors.push(`有 ${failedFiles.length} 张图片上传失败，请重新上传`)
                }

                const oversizedFiles = files.filter(file => file.size > 6 * 1024 * 1024)
                if (oversizedFiles.length > 0) {
                    errors.push('图片大小不能超过6MB')
                }
            }
        }

        generatorState.validationErrors = errors
        return errors.length === 0
    }

    // 构建API请求参数
    const buildRequestParams = () => {
        const config = generatorConfig.value
        const isProVersion = config.taskVersion === 'pro'

        const baseOptions = {
            action: isProVersion ? 'SubmitHunyuanTo3DProJob' : 'SubmitHunyuanTo3DRapidJob',
            EnablePBR: config.commonConfig.enablePBR
        }

        if (isProVersion) {
            baseOptions.FaceCount = config.commonConfig.faceCount
        }

        if (isProVersion) {
            baseOptions.GenerateType = config.commonConfig.generateType
        }

        if (!isProVersion) {
            baseOptions.ResultFormat = config.commonConfig.resultFormat
        }

        if (config.mode === 'text') {
            return {
                url: '/api/v2/generate/text-to-3d',
                method: 'POST',
                data: {
                    prompt: config.textConfig.prompt,
                    options: baseOptions
                }
            }
        } else {
            if (config.imageConfig.type === 'single') {
                const imageFile = config.imageConfig.singleFiles[0]
                return {
                    url: '/api/v2/generate/image-to-3d/url',
                    method: 'POST',
                    data: {
                        image_url: imageFile.uploadedUrl,
                        options: baseOptions
                    }
                }
            } else {
                const frontImage = config.imageConfig.multipleAngles.front
                const multiViewImages = []

                Object.entries(config.imageConfig.multipleAngles).forEach(([viewType, file]) => {
                    if (file && file.uploadedUrl && viewType !== 'front') {
                        multiViewImages.push({
                            ViewType: viewType,
                            ViewImageUrl: file.uploadedUrl
                        })
                    }
                })

                return {
                    url: '/api/v2/generate/image-to-3d/url',
                    method: 'POST',
                    data: {
                        image_url: frontImage.uploadedUrl,
                        options: {
                            ...baseOptions,
                            MultiViewImages: multiViewImages
                        }
                    }
                }
            }
        }
    }

    // 获取图片角度信息
    const getImageAngle = (file, index) => {
        const angles = Object.keys(generatorConfig.value.imageConfig.multipleAngles)
        for (const angle of angles) {
            if (generatorConfig.value.imageConfig.multipleAngles[angle]?.uid === file.uid) {
                return angle
            }
        }
        return `angle_${index}`
    }

    // 更新多张图片配置
    const updateMultipleImagesConfig = () => {
        const files = Object.values(generatorConfig.value.imageConfig.multipleAngles)
            .filter(file => file !== null && file !== undefined)
        generatorConfig.value.imageConfig.multipleFiles = files
        console.log('多张图片配置已更新:', files.length, '张图片')
    }

    // 处理后端API响应数据 - 支持多模型格式选择并保存原始URL
    const processApiResponse = (response, isSubmitResponse = false) => {
        try {
            console.log('处理API响应:', response)

            if (!response) {
                throw new Error('API响应格式错误')
            }

            const apiResponse = response.data

            if (isSubmitResponse) {
                // 处理任务提交响应
                if (!apiResponse.job_id) {
                    throw new Error('未获取到job_id')
                }

                return {
                    success: true,
                    jobId: apiResponse.job_id,
                    requestId: apiResponse.request_id,
                    status: 'submitted',
                    progress: 10,
                    statusText: '任务已提交，正在排队...',
                    currentStep: '任务提交成功'
                }
            } else {
                // 处理任务查询响应
                const taskStatus = apiResponse.Status

                if (taskStatus !== 'DONE') {
                    return {
                        success: true,
                        status: 'processing',
                        progress: getProgressByStatus(taskStatus),
                        statusText: getStatusText(taskStatus),
                        currentStep: getCurrentStep(taskStatus)
                    }
                }

                if (!apiResponse.ResultFile3Ds || apiResponse.ResultFile3Ds.length === 0) {
                    throw new Error('未找到生成的3D模型文件')
                }

                const selectedFile = selectBestModel(apiResponse.ResultFile3Ds)

                if (!selectedFile) {
                    throw new Error('无可用的3D模型文件')
                }

                const originalUrl = selectedFile.Url
                const convertedResultFiles = convertResultFilesToProxy([selectedFile])
                const resultFile = convertedResultFiles[0]

                if (!resultFile.Url) {
                    throw new Error('3D模型文件URL为空')
                }

                logUrlConversion(
                    '处理API响应结果文件',
                    originalUrl,
                    resultFile.Url
                )

                const modelData = {
                    id: apiResponse.RequestId || Date.now().toString(),
                    name: generatorConfig.value.mode === 'text'
                        ? `文生3D-${Date.now()}`
                        : `图生3D-${Date.now()}`,
                    type: generatorConfig.value.mode,
                    format: (resultFile.Type || 'GLB').toLowerCase(),
                    url: resultFile.Url,
                    originalUrl: originalUrl,
                    previewUrl: resultFile.PreviewImageUrl || null,
                    faces: generatorConfig.value.commonConfig.faceCount,
                    vertices: Math.floor(generatorConfig.value.commonConfig.faceCount * 0.6),
                    fileSize: 0,
                    createTime: new Date().toLocaleString(),
                    requestId: apiResponse.RequestId,
                    status: 'completed',
                    downloadUrl: resultFile.Url,
                    availableFormats: apiResponse.ResultFile3Ds.map(f => ({
                        type: f.Type,
                        url: convertToProxyUrl(f.Url),
                        originalUrl: f.Url,
                        previewUrl: f.PreviewImageUrl ? convertToProxyUrl(f.PreviewImageUrl) : null
                    })),
                    selectedFormat: resultFile.Type
                }

                return {
                    success: true,
                    status: 'completed',
                    progress: 100,
                    statusText: '生成完成',
                    currentStep: '模型生成完成',
                    result: modelData,
                    requestId: apiResponse.RequestId
                }
            }

        } catch (error) {
            console.error('处理API响应失败:', error)
            return {
                success: false,
                status: 'failed',
                error: error.message,
                statusText: '生成失败，请重试'
            }
        }
    }

    // 根据状态获取进度
    const getProgressByStatus = (status) => {
        const statusMap = {
            'SUBMITTED': 20,
            'PROCESSING': 60,
            'DONE': 100,
            'FAILED': 0
        }
        return statusMap[status] || 10
    }

    // 根据状态获取状态文本
    const getStatusText = (status) => {
        const statusMap = {
            'SUBMITTED': '任务已提交，正在排队...',
            'PROCESSING': '正在生成3D模型...',
            'DONE': '生成完成',
            'FAILED': '生成失败'
        }
        return statusMap[status] || '处理中...'
    }

    // 根据状态获取当前步骤
    const getCurrentStep = (status) => {
        const stepMap = {
            'SUBMITTED': '准备生成',
            'PROCESSING': '模型生成',
            'DONE': '生成完成',
            'FAILED': '生成失败'
        }
        return stepMap[status] || '处理中'
    }

    // 估算面数
    const estimateFaceCount = (faceCount) => {
        return faceCount
    }

    // 估算顶点数
    const estimateVertexCount = (faceCount) => {
        return Math.floor(faceCount * 0.6)
    }

    // 停止轮询
    const stopPolling = () => {
        pollingState.isPolling = false
        if (pollingState.pollInterval) {
            clearTimeout(pollingState.pollInterval)
            pollingState.pollInterval = null
        }
        pollingState.currentAttempt = 0
    }

    // 获取任务状态API调用 - 传递requestId
    const getTaskStatus = async (jobId, requestId) => {
        console.log('[useGenerator] 查询任务状态:', { jobId, requestId })
        const response = await request.get(`/api/v2/task/status/${jobId}`, {
            requestId,
        })
        return response
    }

    // 轮询任务状态 - 修改版本，添加评估报告请求
    const pollTaskStatus = async (jobId, requestId) => {
        pollingState.isPolling = true
        pollingState.currentAttempt = 0

        const poll = async () => {
            try {
                pollingState.currentAttempt++

                // 发送进度事件
                modelEventBus.emitGenerateProgress({
                    progress: generatorState.progress,
                    statusText: generatorState.statusText,
                    currentStep: generatorState.currentStep
                })

                const response = await getTaskStatus(jobId, requestId)
                const processedResponse = processApiResponse(response, false)

                if (processedResponse.success) {
                    generatorState.progress = processedResponse.progress
                    generatorState.statusText = processedResponse.statusText
                    generatorState.currentStep = processedResponse.currentStep

                    if (processedResponse.status === 'completed') {
                        generatorState.status = 'completed'
                        generatorState.result = processedResponse.result
                        generatorState.isGenerating = false

                        // 关键修改：在生成成功后调用更新记录接口，使用原始URL
                        try {
                            console.log('[useGenerator] 开始更新生成记录，requestId:', processedResponse.requestId)

                            const recordUpdateData = {
                                ...processedResponse.result,
                                url: processedResponse.result.originalUrl || getOriginalUrl(processedResponse.result.url)
                            }

                            await updateGenerationRecord(recordUpdateData, processedResponse.requestId)
                            console.log('[useGenerator] 生成记录更新成功')
                        } catch (updateError) {
                            console.error('[useGenerator] 更新生成记录失败，但不影响主流程:', updateError)
                        }

                        // 关键：使用 EventBus 发送生成成功事件
                        modelEventBus.emitGenerateSuccess(processedResponse.result)
                        setCurrentModel(processedResponse.result)

                        // 刷新历史记录而不是添加到本地
                        await refreshHistory()

                        stopPolling()

                        ElMessage.success('3D模型生成完成！')
                        console.log('✅ 生成任务完成:', processedResponse.result)

                        // 新增：在生成成功后建立SSE连接并请求评估报告
                        const userId = userStore.userInfo.userId
                        if (userId) {
                            // 建立SSE连接（如果还未建立）
                            if (!sseState.isConnected) {
                                establishSSEConnection(userId)
                            }

                            // 请求生成评估报告 - 修改：添加参考图片
                            const currentPrompt = generatorConfig.value.mode === 'text'
                                ? generatorConfig.value.textConfig.prompt
                                : '基于图片生成的3D模型'

                            // 获取参考图片URL
                            const referenceImageUrl = getReferenceImageUrl()

                            console.log('[评估] 准备请求评估，参考图片URL:', referenceImageUrl)

                            await requestEvaluationReport(processedResponse.result, currentPrompt, referenceImageUrl)
                        }

                    } else if (processedResponse.status === 'failed') {
                        throw new Error(processedResponse.error || '生成失败')

                    } else {
                        if (pollingState.currentAttempt < pollingState.maxPollAttempts) {
                            pollingState.pollInterval = setTimeout(poll, 30000)
                        } else {
                            throw new Error('生成超时，请重试')
                        }
                    }
                } else {
                    throw new Error(processedResponse.error || '查询任务状态失败')
                }

            } catch (error) {
                console.error('轮询任务状态失败:', error)
                generatorState.error = error.message
                generatorState.status = 'failed'
                generatorState.statusText = '生成失败，请重试'
                generatorState.isGenerating = false

                modelEventBus.emitModelError(error)

                stopPolling()
                ElMessage.error(error.message)
            }
        }

        poll()
    }

    // 格式化面数
    const formatFaceCount = (count) => {
        if (count >= 10000) {
            return Math.round(count / 10000) + '万'
        } else if (count >= 1000) {
            return Math.round(count / 1000) + 'K'
        }
        return count.toString()
    }

    // 生成3D模型主方法 - 保存并传递requestId
    const handleGenerate = async () => {
        try {
            console.log('=== 开始生成3D模型 ===')

            if (!validateForm()) {
                console.error('表单验证失败:', generatorState.validationErrors)
                ElMessage.error(generatorState.validationErrors[0])
                return
            }

            console.log('✓ 表单验证通过')

            generatorState.isGenerating = true
            generatorState.progress = 0
            generatorState.status = 'pending'
            generatorState.error = null
            generatorState.statusText = '正在提交任务...'
            generatorState.currentStep = '准备提交'

            modelEventBus.emitGenerateStart(generatorConfig.value)

            const requestConfig = buildRequestParams()
            console.log('API请求配置:', JSON.stringify(requestConfig, null, 2))

            generatorState.statusText = '正在生成3D模型...'
            generatorState.status = 'processing'
            generatorState.currentStep = '模型生成'

            const response = await request.post(requestConfig.url, {
                ...requestConfig.data,
                user_id: userStore.userInfo.userId
            })
            console.log('生成任务响应:', response)

            const processedResponse = processApiResponse(response, true)

            if (processedResponse.success) {
                generatorState.jobId = processedResponse.jobId
                generatorState.requestId = processedResponse.requestId
                generatorState.progress = processedResponse.progress
                generatorState.statusText = processedResponse.statusText
                generatorState.currentStep = processedResponse.currentStep

                console.log('✓ 任务提交成功, JobID:', generatorState.jobId, 'RequestID:', generatorState.requestId)

                await pollTaskStatus(generatorState.jobId, generatorState.requestId)
            } else {
                throw new Error(processedResponse.error || '生成失败')
            }

        } catch (error) {
            console.error('生成失败:', error)
            generatorState.error = error.message
            generatorState.status = 'failed'
            generatorState.statusText = '生成失败，请重试'
            generatorState.currentStep = '生成失败'
            generatorState.isGenerating = false

            modelEventBus.emitModelError(error)

            ElMessage.error(error.message)
        }
    }

    // 设置生成模式
    const setMode = (mode) => {
        console.log('切换生成模式:', generatorConfig.value.mode, '->', mode)
        generatorConfig.value.mode = mode
        generatorState.validationErrors = []

        if (mode === 'text') {
            generatorConfig.value.imageConfig.singleFiles = []
            generatorConfig.value.imageConfig.multipleFiles = []
            generatorConfig.value.imageConfig.multipleAngles = {
                front: null, back: null, left: null, right: null, top: null, bottom: null
            }
        } else {
            generatorConfig.value.textConfig.prompt = ''
        }
    }

    // 设置任务版本
    const setTaskVersion = (version) => {
        console.log('切换任务版本:', generatorConfig.value.taskVersion, '->', version)
        generatorConfig.value.taskVersion = version
    }

    // 加载历史模型 - 使用新的历史记录Hook
    const loadHistoryModel = (historyItem) => {
        console.log('加载历史模型:', historyItem.name)

        const modelData = {
            id: historyItem.id,
            name: historyItem.name,
            type: historyItem.type,
            faces: parseInt(historyItem.faces.replace(/[^\d]/g, '')) * (historyItem.faces.includes('万') ? 10000 : historyItem.faces.includes('K') ? 1000 : 1) || 50000,
            vertices: Math.floor(Math.random() * 50000) + 10000,
            fileSize: historyItem.fileSize,
            downloadUrl: historyItem.downloadUrl,
            format: historyItem.format || 'glb',
            createTime: historyItem.createTime,
            previewUrl: historyItem.thumbnail,
            url: historyItem.downloadUrl,
            availableFormats: historyItem.availableFormats || [],
            selectedFormat: historyItem.selectedFormat || historyItem.format
        }

        const convertedModelData = convertModelDataToProxy(modelData)

        logUrlConversion('加载历史模型', modelData.url, convertedModelData.url)

        modelEventBus.emitHistoryItemSelected(convertedModelData)
        setCurrentModel(convertedModelData)

        ElMessage.success(`已加载模型: ${historyItem.name}`)
    }

    // 切换模型格式
    const switchModelFormat = (formatType, modelData) => {
        if (!modelData.availableFormats || modelData.availableFormats.length === 0) {
            console.warn('该模型没有其他可用格式')
            return
        }

        const targetFormat = modelData.availableFormats.find(f => f.type === formatType)
        if (!targetFormat) {
            console.warn(`未找到 ${formatType} 格式的模型`)
            ElMessage.warning(`该模型不支持 ${formatType} 格式`)
            return
        }

        const newModelData = {
            ...modelData,
            format: formatType.toLowerCase(),
            url: targetFormat.url,
            downloadUrl: targetFormat.url,
            previewUrl: targetFormat.previewUrl || modelData.previewUrl,
            selectedFormat: formatType,
            originalUrl: targetFormat.originalUrl || getOriginalUrl(targetFormat.url)
        }

        console.log(`切换模型格式: ${modelData.selectedFormat} -> ${formatType}`)

        setCurrentModel(newModelData)

        ElMessage.success(`已切换到 ${formatType} 格式`)
    }

    // 计算属性
    const canGenerate = computed(() => {
        if (generatorState.isGenerating) return false

        if (generatorConfig.value.mode === 'text') {
            return generatorConfig.value.textConfig.prompt.trim().length > 0
        } else {
            if (generatorConfig.value.imageConfig.type === 'single') {
                const files = generatorConfig.value.imageConfig.singleFiles
                return files.length === 1 && files[0].uploadedUrl
            } else {
                const files = generatorConfig.value.imageConfig.multipleFiles
                const frontImage = generatorConfig.value.imageConfig.multipleAngles.front
                return files.length >= 2 && frontImage && files.every(file => file.uploadedUrl)
            }
        }
    })

    const generateTip = computed(() => {
        if (generatorState.validationErrors.length > 0) {
            return generatorState.validationErrors[0]
        }

        if (generatorConfig.value.mode === 'text') {
            const prompt = generatorConfig.value.textConfig.prompt.trim()
            if (!prompt) return '请输入文本描述'
            return ''
        } else {
            if (generatorConfig.value.imageConfig.type === 'single') {
                const files = generatorConfig.value.imageConfig.singleFiles
                if (files.length === 0) return '请上传一张图片'
                if (!files[0].uploadedUrl) return '等待图片上传完成...'
                return ''
            } else {
                const files = generatorConfig.value.imageConfig.multipleFiles
                if (files.length < 2) return '请至少上传2张图片'
                if (!generatorConfig.value.imageConfig.multipleAngles.front) return '请上传正面视角图片'
                const unuploadedCount = files.filter(file => !file.uploadedUrl).length
                if (unuploadedCount > 0) return `还有 ${unuploadedCount} 张图片正在上传...`
                return ''
            }
        }
    })

    // 监听器
    watch(generatorConfig, () => {
        validateForm()
    }, { deep: true })

    watch(() => generatorConfig.value.mode, (newMode) => {
        console.log('生成模式已切换至:', newMode)
        validateForm()
    })

    // 生命周期清理
    const cleanup = () => {
        stopPolling()
        closeSSEConnection()
        modelEventBus.off('useGenerator')
        console.log('useGenerator 清理完成')
    }

    // 返回接口
    return {
        // 配置和状态（响应式）
        generatorConfig,
        generatorState,
        currentModel,
        pollingState,
        sseState,

        // 历史记录相关（来自新的Hook）
        historyList,
        historyState,
        filterState,
        filteredHistory,
        totalSize,
        statusStats,
        typeStats,

        // 计算属性
        canGenerate,
        generateTip,

        // 核心方法
        setMode,
        setTaskVersion,
        handleGenerate,
        validateForm,
        buildRequestParams,
        loadHistoryModel,
        setCurrentModel,
        switchModelFormat,
        updateGenerationRecord,
        getOriginalUrl,
        getReferenceImageUrl,

        // 历史记录管理方法（来自新的Hook）
        fetchHistoryRecords,
        refreshHistory,
        loadMoreHistory,
        initializeHistory,
        setFilters,
        setSortBy,
        deleteHistoryRecord,
        updateStarStatus,
        findRecordById,
        addNewRecord,

        // 工具方法
        getImageAngle,
        formatFaceCount,
        processApiResponse,
        getProgressByStatus,
        getStatusText,
        getCurrentStep,
        estimateFaceCount,
        estimateVertexCount,
        selectBestModel,
        updateMultipleImagesConfig,

        // 历史记录工具方法（来自新的Hook）
        transformHistoryData,
        formatFileSize,
        getStatusTagType,
        getStatusLabel,
        getTypeLabel,
        getStatusColor,
        getTypeColor,

        // 轮询控制
        pollTaskStatus,
        stopPolling,
        getTaskStatus,

        // SSE和评估相关方法
        establishSSEConnection,
        closeSSEConnection,
        requestEvaluationReport,
        handleSSEMessage,

        // 清理方法
        cleanup
    }
}